package com.wenyang.utils;

import java.io.*;
import java.net.*;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

public class FileUploadUtil {

        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;

        public FileUploadUtil(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
            this.endpoint = endpoint;
            this.accessKeyId = accessKeyId;
            this.accessKeySecret = accessKeySecret;
            this.bucketName = bucketName;
        }

        public void FileUploadUtil(File imageFile, String objectKey) {
            // 初始化OSSClient
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            try {
                // 上传文件到指定的OSS Bucket
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectKey, imageFile);
                PutObjectResult result = ossClient.putObject(putObjectRequest);

                // 可以通过result获取上传结果的信息
                System.out.println("ETag: " + result.getETag());

            } catch (OSSException oe) {
                oe.printStackTrace();
            } catch (ClientException ce) {
                ce.printStackTrace();
            } finally {
                // 关闭客户端
                ossClient.shutdown();
            }
        }
}
